<?php

define('XLS_STATUS_NONE',  0);
define('XLS_STATUS_WRITE', 1);
define('XLS_STATUS_READ',  2);
define('XLS_STATUS_EOF',   3);

/**
 * Implémentation  pour un fichier xls
 *
 * @category Framework
*/
class CWriteXls 
{
	var $filename;
	var $separator;
	var $columnsHeader;

	var $file;
	var $workbook;			// object: class "Spreadsheet_Excel_Reader"(si ecriture), class "writeexcel_workbookbig"(si lecture)
	var $sheets;			// Array : feuille du doc
	var $worksheet;			// Array : feuille courante
	var $current_line;		// int   : indice ligne courante
	var $current_row;		// Array : ligne courante
	var $status;		
	var $has_header;
	var $filePath;

	/**
	 * Constructeur
	 *
	 * @param String $filename       : Nom du fichier de sortie
	 * @param bool   $has_header     : Si nom de colonnes fourni ou pas
	 * @param Array  $columns        : Nom des colonnes
	 * @param int    $worksheetnumber: Numero feuille courante
	 * @param string $status	 : lecture("r")/ecriture("w")
	 */
	function CWriteXls($filename,$has_header=true,$columns=0,$worksheetnumber=0)
	{
		$this->filename=$filename;
		$this->has_header=$has_header;
		$this->status=XLS_STATUS_NONE;
		$this->columnsHeader=$columns;
		$this->current_row=0;
		$this->current_line=0;
		
		$this->filePath = '../generated/statistique/'.$filename;
	
			if (file_exists($this->filePath))
				unlink($this->filePath);
				
			$this->file = fopen($this->filePath, "w");
			$this->workbook = new writeexcel_workbook($this->file); //new writeexcel_workbookbig($this->file);
			$this->workbook->set_tempdir(getcwd());			// dir courant pour les fichiers temporaires
			$this->worksheet = $this->workbook->addworksheet();

			if(is_array($columns))	// si entete fourni
			{
				$this->worksheet->write_row($this->current_line, 0, $this->columnsHeader,"");	
				$this->current_line++;
				$this->status=XLS_STATUS_WRITE;
			}
		
		register_shutdown_function(array($this,"__destruct"));
	}

	function __destruct()
	{
		if ($this->file !== false)
		{
			if($this->status==XLS_STATUS_READ)
				fclose($this->file);
			elseif($this->status==XLS_STATUS_WRITE)
				$this->workbook->close();
			$this->file = false;
		}
	}

	function fetchNext()
	{
		if ($this->status==XLS_STATUS_NONE)
		{
			if (!file_exists($this->filename))
				die ("ERREUR CWriteXls::fetchNext erreur de fichier ({$this->filename})");
			//$this->file=fopen($this->filename,"r");
			if ($this->file && is_array($this->worksheet))
			{
				if ($this->has_header)
				{
					$keys_tmp=array_keys($this->worksheet["cells"]);
					$this->current_line=$keys_tmp[0];
					$this->columnsHeader = $this->worksheet["cells"][0];
					$this->current_line++;
				}

				$this->status=XLS_STATUS_READ;
			}
			else
				die ("ERREUR CWriteXls::fetchNext erreur de fichier ({$this->filename})");
		}
		unset($tmpArr);
		$this->current_row = $this->worksheet["cells"][$this->current_line];
		 
		if (!is_array($this->current_row))
			return false;
			
		foreach($this->current_row as $key=>$value)
		{

			if ($this->has_header)
				$tmpArr[$this->columnsHeader[$key]] = $value;
			else
				$tmpArr[$key] = $value;
			//echo $this->columnsHeader[$key].": ".$tmpArr[$this->columnsHeader[$key]]."<br>";
		}
		$this->current_row = $tmpArr;
		
		if($this->current_line < $this->worksheet["numRows"])
			$this->current_line++;
		else
		{
			$worksheetnumber++;
			$this->worksheet=$this->sheets[$worksheetnumber];
//			TODO Enlever @
			$keys_tmp=@array_keys($this->worksheet["cells"]);
			$this->current_line=(!($this->has_header)) ? $keys_tmp[0] : $keys_tmp[1];
		}
		return ($this->current_row!==false);
	}


	function writeNext($data_row)
	{
		if ($this->status==XLS_STATUS_NONE)
		{
			if ($this->columnsHeader==0)
			{
				$this->columnsHeader=array();
				foreach($data_row as $key=>$value)
					$this->columnsHeader[]=$key;
			}

			$this->file=fopen($this->filename,"w");
			if ($this->file)
				$this->status=XLS_STATUS_WRITE;
			else
				die("ERREUR CWriteXls::writeNext erreur de fichier (".$this->filename.")");	 // TODO

			$this->status=XLS_STATUS_WRITE;

			// Ecrire le header si besoin
			if ($this->has_header)
			{
				if(is_array($this->columnsHeader))
				{
					$this->worksheet->write_row($this->current_line, 0, $this->columnsHeader,"");	
					$this->current_line++;
				}
			}


		}

		if ($this->status == XLS_STATUS_WRITE)
		{
			if(count($data_row)>0)
			{
				
				$this->worksheet->write_row($this->current_line, 0, $data_row,"");	
				$this->current_line++;
			}
		}
		else
			die('Etat de l objet xls incorrect pour ecriture ('.$this->status.')');
	}

	function getData($data_name)
	{
		// TODO current_row ne correspond
		return (isset($this->current_row[$data_name])) ? $this->current_row[$data_name] : false ;
	}

	function getCurrentRow()
	{
		return $this->current_row;
	}
	
	function writeFromArray(&$aData, $rows=-1)
	{
		if (is_array($aData))
		{
			$count=0;
			foreach($aData as $iKey => $aDataRow)
			{
				/*if (array_key_exists('OFFRE',$aDataRow))	$aDataRow['OFFRE'] = utf8_decode($aDataRow['OFFRE']);
				if (array_key_exists('PRODUIT',$aDataRow))	$aDataRow['PRODUIT'] = utf8_decode($aDataRow['PRODUIT']);
				if (array_key_exists('FORMULE',$aDataRow))	$aDataRow['FORMULE'] = utf8_decode($aDataRow['FORMULE']);
				if (array_key_exists('REGION',$aDataRow))	$aDataRow['REGION'] = utf8_decode($aDataRow['REGION']);
				if (array_key_exists('UNITE',$aDataRow))	$aDataRow['UNITE'] = utf8_decode($aDataRow['UNITE']);
				if (array_key_exists('AGENT',$aDataRow))	$aDataRow['AGENT'] = utf8_decode($aDataRow['AGENT']);
*/				
	if($count!=$rows)
				{
					$this->writeNext($aDataRow);
					$count++;
				}
			}
		}
		
		return $count;
	}
	
	public function sendXlsByMail($sDestinataire)
		{
		  	$mail = new PHPMailer();
		  	
		    $mail->IsHTML(true);
		    $mail->IsSendmail();
		    //$mail->IsSMTP();
		   // $mail->Host = "smtp.ds2i-offshore.com:465"; 
		    $mail->SetLanguage('fr', './mail/language/');
		    
		    $mail->From='sfatim@ds2i-offshore.com';

		    $mail->AddAddress($sDestinataire);
		    $mail->AddReplyTo('sfatim@ds2i-offshore.com');    
		    $mail->Subject = "Envoi d'élément statistique logiciel Microassur";
		    //$sNameZip = $this->filePath.'.zip';
		    //exec('zip '.$sNameZip.' '.$this->filePath);
		    $mail->Body='<html><body><center><font size=4>Vous avez demand&eacute; &agrave; re&ccedil;evoir cet &eacute;l&egrave;ment statistique :<br> Voir le fichier attach&eacute;<br></body></html>';

		    $sRealPath = PATH_APPLI.'generated/statistique/'.$this->filename;
		    exec ('chmod 777 '.$sRealPath);
		    //$fp = fopen($sRealPath, "r");  
			$attachement = fread($this->file, 8192);
			//fclose($fp);

			$attachement = chunk_split(base64_encode($attachment));
		    echo "<br>$sRealPath file existe::".var_dump(file_exists($sRealPath))."<br>";
		    echo "<br>$this->filePath file existe relative::".var_dump(file_exists($this->filePath))."<br>";
		    //$attachement = file_get_contents($sRealPath);
		    //$mail->AddAttachment($sRealPath, $this->filename, 'base64', 'application/msexcel');
		    $mail->AddStringAttachment($attachement, $this->filename, 'base64', 'application/msexcel');
			
			if(!$mail->Send()) 
			{
				$sRetour = "Mailer Error: " . $mail->ErrorInfo;
	  			
			} else 
			{
	  			$sRetour = "Elèment statistique envoyé par mail!";
			}
			
		    //$sRetour = "send";
			unset($mail);
			
		   return $sRetour;
		}

}

?>
